var request = require('request');
var cheerio = require('cheerio');
var md5 = require("md5");
var mysql = require('mysql');
var moment = require('moment');
 var db = require('./data/config');
 var connection = mysql.createConnection({
 	host: db.host,
 	user: db.user,
 	password: db.password,
 	database:db.database
 });



var options = {
	url: 'http://cdfgj.gov.cn/SCXX/Default.aspx',
	method: 'GET',
	charset: "utf-8",
	headers: {
		"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36",
	}
};

request(options, function(err, result) {
	if (err) {
		console.log(err);
	}
	 console.log(result.body);

	var $ = cheerio.load(result.body);

	var nowDate = new Date();
	var gtime = nowDate.toLocaleDateString() + " " + nowDate.toLocaleTimeString();
	var adate = nowDate.toLocaleDateString();

	 connection.connect();

	var addSql = 'INSERT IGNORE  INTO cdfgj_trade(traderdate,areas,totals,housenum,housetotals,isones,hashs) VALUES(?,?,?,?,?,?,?)';
	// var addSqlParams = ['菜鸟工具', 'https://c.runoob.com', '23453', 'CN'];



	$('tr[bgcolor="#FFFFFF"]').each(function(index, element) {

		// console.log('------------');
		// console.log(index);
		var re = $(element).text().toString().replace(/\s+/g, ',').split(',');
                console.log(re);
		// re[0] = '2017-10-10';
		re[0] = moment().format('YYYY-MM-DD');
		//

		//re[6] = md5(re[0]+re[1]+re[5]);
		re[7] = gtime;
		if (index <= 5) {
			// console.log('一手房');
			re[5] = '1';

		} else {
			// console.log('二手房');
			re[5] = '2';
		}

		re[6] = md5(re[0]+re[1]+re[5]);
		console.log(re);

        //console.log(re);
		//增
		 connection.query(addSql, re, function(err, result) {
		 	if (err) {
		 		console.log('[INSERT ERROR] - ', err.message);
		 		return;
		 	}
        //
		 	//console.log('--------------------------INSERT----------------------------');
		 	//console.log('INSERT ID:',result.insertId);
		 	//console.log('INSERT ID:', result);
		 	//console.log('-----------------------------------------------------------------\n\n');
		 });

	})
 connection.end();
})
